extends CharacterBody2D

@onready var enemy_anim:AnimatedSprite2D = $EnemyAnimation
@onready var enemy_anim_player:AnimationPlayer = $EnemyAnimationPlayer
@onready var enemy_animation_tree:AnimationNodeStateMachinePlayback = $EnemyAnimationTree.get("parameters/playback")

@export var patrol_range: float = 100  # 巡逻范围
@export var move_speed: float = 50    # 移动速度
@export var health = 2  # 新增生命值属性

var target_position := handle_patrol_position()
var move_direction: int = 1
var player: Node2D = null
var is_chasing: bool = false
var gravity := 980.0

var is_dead := false  # 新增死亡状态标识

func _ready():
	enemy_animation_tree.start("new")
	target_position = handle_patrol_position()

func _physics_process(delta: float) -> void:
	if is_dead: 
		return  # 如果已经死亡，不再执行任何逻辑
	# 检测“死亡动画”是否播放完毕
	if health <= 0 and not enemy_anim_player.is_playing():
		is_dead = true
		await get_tree().create_timer(1.0).timeout  # 等待1秒
		queue_free()
		return
	# 检测“创建动画”是否播放完毕
	if enemy_animation_tree.get_current_node() == "new" and not enemy_anim_player.is_playing():
		# 过渡到“空闲动画”
		enemy_animation_tree.travel("idle")
		return
	# 检测“受伤动画”是否播放完毕
	if enemy_animation_tree.get_current_node() == "hurt" and not enemy_anim_player.is_playing():
		# 过渡到“空闲动画”
		enemy_animation_tree.travel("idle")
		return
	update_character_direction(move_direction)
	patrol(delta)
	track_player(delta)

func handle_fall(delta):
	if not is_on_floor():
		velocity.y += gravity * delta
		# 限制最大下落速度防止穿模
		velocity.y = min(velocity.y, 2000)

func patrol(delta):
	if !player:
		position = position.move_toward(target_position, move_speed * delta)
	if position.distance_to(target_position) < 1 and patrol_range != 0:
		move_direction *= -1 
		target_position = handle_patrol_position()

func track_player(delta):
	if player:
		var y := position.y
		position = position.move_toward(Vector2(player.position.x, y), move_speed * delta)

# 新增顶部碰撞检测（角色踩踏）
func _on_top_hitbox_body_entered(body):
	if body.is_in_group("player"):
		take_damage()
		enemy_animation_tree.travel("hurt")
		EventBus.emit_signal("player_jump")

# 新增侧边碰撞检测（左右接触）
func _on_side_hitbox_body_entered(body, direction = -1):
	if body.is_in_group("player"):
		print(direction)
		EventBus.emit_signal("player_hurt", direction)	

# 新增受伤处理
func take_damage():
	if is_dead: 
		return  # 如果已经死亡，不再响应伤害
	health -= 1

func handle_patrol_position() -> Vector2:
	return position + Vector2(patrol_range * move_direction, 0)

func update_character_direction(direction: float):
	if player:
		var enemy_direction := position.x - player.position.x
		if enemy_direction > 0:
			direction = -1
		else:
			direction = 1
	if direction != 0:
		enemy_anim.flip_h = direction < 0

func _on_track_player_clear(body):
	if body.is_in_group("player"):
		player = null

func _on_track_player(body):
	if body.is_in_group("player"):
		player = body
